PageViewEvent = RegisterEvents{
    "OnPageChanged"
}
PageView = {
    props = {
        _pageIndex = 0,
        pageMax = 0
    },
    gets = {
        pageIndex = function (self)
            return self._pageIndex
        end,
        tabs = function (self)
            return self._tabs
        end
    },
    sets = {
        pageIndex = function (self, key, val)
            local old = self._pageIndex
            self._pageIndex = val
            self:emit(PageViewEvent.OnPageChanged, val, old)
        end,
        tabs = function (self, key, val)
            if self._tabs then
                self._tabs:off(SwitchGroupEvent.Selected, self._onTabSelected, self)
            end
            self._tabs = val
            if val then
                val:on(SwitchGroupEvent.Selected, self._onTabSelected, self)
                self.pageIndex = val.selectedSwitchIndex
            end

        end
    }
}

function PageView:_onTabSelected(index)
    self.pageIndex = index
end
local function OnPageChanged(page, val)
    page.active = val == page.pageIndex
end
function Node.PageView(args)
    local view = Node.new():addComponent(PageView):addComponent(Stretch)
    view.name = "PageView"
    view.pageMax = #args

    for i, v in ipairs(args) do
        local page = Node.new():addTo(view)
        page:addComponent(Stretch)
        page.color = v.color or Color.white
        page.pageIndex = i
        page.name = "Page"..i
        view:on(PageViewEvent.OnPageChanged, OnPageChanged, page)
        if v.view then
            page:add(v.view)
        end
    end
    return view
end

function Node.ScrollPageView(args)
    local view = Node.ScrollView()
    view:addComponent(PageView)
    view.name = "PageView"
    view.pageMax = #args
    view:addComponent(Stretch)
    view.scrollContent:addComponent(Layout)
    local layout = view.scrollContent
    layout.layoutType = LayoutType.Horizontal
    layout:addComponent(Stretch)
    layout.stretchPercentX = #args
    view.layout = layout
    layout:addComponent(Drag)
    layout:on(NodeEvent.OnDragEnded, function ()
        local p = view.scrollPercentX * (#args - 1)
        view.pageIndex = math.round(p) + 1
    end)

    local p = 1/ #args
    for i, v in ipairs(args) do
        local page = Node.new():addTo(layout)
        page:addComponent(Stretch)
        page:addComponent(Sprite)
        page.touchSwallowed = false
        page.stretchPercentX = p
        page.color = v.color or Color.white
        if v.view then
            page:add(v.view)
        end
    end
    return view
end